<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace response;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use ShidianUtil\Utils\StringUtil;
use think\response\File;

/**
 * File Response
 */
class Excel extends File
{
    public function __construct(Spreadsheet $data, $name)
    {
        parent::__construct($data);
        $this->name = $name;
    }

    /**
     * 处理数据
     * @access protected
     * @param mixed $data 要处理的数据
     * @return mixed
     * @throws \Exception
     */
    protected function output($data)
    {
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        $name = $this->name;
        $name = rawurlencode(mb_substr($name, 0, 55));
        if (!StringUtil::contains($name, '.')) {
            $name .= '.xlsx';
        }

        $this->header['Pragma'] = 'public';
        $this->header['Content-Type'] = 'application/vnd.ms-excel';
        // $this->header['Content-Type'] = $mimeType ?: 'application/octet-stream';
        $this->header['Cache-control'] = 'max-age=' . $this->expire;
        $this->header['Content-Disposition'] = ($this->force ? 'attachment; ' : '') . 'filename="' . $name . '"';
        // $this->header['Content-Length'] = $size;
        $this->header['Content-Transfer-Encoding'] = 'binary';
        $this->header['Expires'] = gmdate("D, d M Y H:i:s", time() + $this->expire) . ' GMT';

        $this->lastModified(gmdate('D, d M Y H:i:s', time()) . ' GMT');

        return null;
    }

    /**
     * 输出数据
     * @access protected
     * @param string $data 要处理的数据
     * @return void
     */
    protected function sendData(string $data): void
    {
        $xmlWriter = IOFactory::createWriter($this->data, 'Xlsx');
        $xmlWriter->save("php://output");
    }

}
